import { getStorage, setStorage } from '@/utils/storage'
import { getToken } from '@/utils/user'

/**
 * 设置本地用户数据
 */
export const setUsers = (users) => {
  setStorage('users', JSON.stringify(users))
  return users
}
/**
 * 获取本地用户数据
 */
export const getUsers = () => getStorage('users') ? JSON.parse(getStorage('users')) : []

/**
 * 用户登录， 先校验是否在数据库
 */
export const userLogin = ({ number, password }) => {
  const user = getUsers().find(item => item.number === number)

  if (user) {
    return user
  }

  const template = {
    name: '沈阳阳',
    email: 'shengyang@gmail.com',
    age: '',
    role: '', // parent, child, younger
    number,
    password,
    avatar: 'https://aha-public-1301319986.cos.ap-shanghai.myqcloud.com/static_file/yuping/userAvatar/20220308094833150-Ellipse 13.png',
    avatarLarge: 'https://aha-public-1301319986.cos.ap-shanghai.myqcloud.com/static_file/yuping/userAvatar/20220312153807850-Ellipse 13 (3).png',
    ageRange: null,
    sex: null,
    toys: null,
    interest: null,
  }
  const users = getUsers().concat(template)

  setUsers(users)
  return template
}

/**
 * 更新我的信息
 */
export const putMyInfo = (user) => {
  const users = getUsers()
  const index = users.findIndex(item => item.number === user.number)

  users[ index ] = user

  setUsers(users)
}

/**
 * token登录
 */
export const tokenLogin = () => {
  if (getToken()) {
    const userNumber = getToken()
    const user = getUsers().find(item => item.number === userNumber)

    if (user) {
      Vue.prototype.$storeCommit('setUserInfo', user)
      return user
    }
  }
  return null
}
